package com.fingard.dsp.bank.directbank.crbc01;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.bankInterface.IReceiptPro;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.dsp.task.command.SyncReceipt;
import com.fingard.io.FileCheckHelper;
import com.fingard.io.FileHelper;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.util.ZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CRBC01ReceiptPro extends CRBC01Base implements IReceiptPro {

	public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay)
			throws Exception {
		
		String qryDay8 = Format.Date8Format.format(pOneDay);
		int lastIdx = bankFront.serverURL.lastIndexOf('/');
		String serverURL = "";
		if(lastIdx>0){
			serverURL = bankFront.serverURL.substring(0, bankFront.serverURL.lastIndexOf('/'));
		}else{
			serverURL = bankFront.serverURL;
		}
		serverURL += "/download?action=200007EProofDownload&cust_account=" + pReqReceipt.actNum + "&queryDate=" + qryDay8;
        WriteBankLogLn("2.提交银行的地址：" + serverURL);
        String timePostfix = getQryTransID();
        String fileFix = pConfig.getSaveSubDir(pReqReceipt.reqHeader, pOneDay)+File.separator+pReqReceipt.actNum + "_" + qryDay8;
        String zipFilePath = fileFix  + "_" + timePostfix + ".zip";
        String doneFilePath = fileFix+".done";
        if(FileHelper.existFile(doneFilePath)){
        	WriteBankLogLn("已存在文件"+doneFilePath+"，如需重新下载，请删除该文件");
        }else{
        	//开通电子回单
        	openReceipt();
        	if(FileHelper.deleteFileIfExists(zipFilePath));
        	WebRequest webReq = new WebRequest(serverURL);
        	String[] downRet = webReq.download(zipFilePath);
        	if(downRet[0].length() == 0 && FileHelper.existFile(zipFilePath)){
        		String tmpDecompressDir = fileFix;
        		File depressDir = new File(tmpDecompressDir);
        		if(!depressDir.exists()){
            		depressDir.mkdirs();
            	}
                WriteBankLogLn("解压至：[" + tmpDecompressDir + "]");
                ZipHelper.unzipFile(zipFilePath, tmpDecompressDir);
                WriteBankLogLn("执行解压结束");
                if (depressDir.exists()) {
                	if(getReceiptFiles(pConfig, pReqReceipt, pOneDay, depressDir)){
                		SyncReceipt.resetDelayCounter();//同步任务重新计数延时
                		//下载完成，当天的不算结束
                		if(!DateHelper.isSameDay(pOneDay, new Date())){
                			FileHelper.writeFile(doneFilePath, Format.DateTimeFormat.format(new Date()), "utf-8");
                		}
                	}
                } else {
                	WriteBankLogLn("解压目标文件夹" + tmpDecompressDir + "不存在，创建失败");
                }
        	}else if(downRet[0].length() > 0){
        		WriteBankLogLn("下载失败："+StringHelper.joinNotEmpty("-", downRet));
        	}else{
        		WriteBankLogLn("通讯成功，保存文件失败："+zipFilePath);
        	}
        }
        if(pConfig.deleteAfterUploaded){
        	FileHelper.deleteFileIfExists(zipFilePath);
        }
		return null;
	}
	
	private void openReceipt() throws Exception{
		if(this.getBankConfig().getValueAsBool("isOpenReceipt")){
			String chkFilePath = FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "markData" + File.separator + this.bankFront.bankCode;
            chkFilePath = chkFilePath + File.separator + StringHelper.joinNotEmpty("_", "OpenReceipt",bankFront.tenant,bankFront.corporation,bankFront.code)+".txt";
			if(FileHelper.existFile(chkFilePath)){
				WriteBankLogLn("电子回单已经开通成功，如需再次开通，请删除文件"+chkFilePath);
				return;
			}
			WriteBankLogLn("发送开通电子回单请求");
            XmlTextWriter xmlWriter = new XmlTextWriter();
            CRBC01Header bankHeader = new CRBC01Header();
            bankHeader.tranCode = "200007";
            bankHeader.tranTime = new Date();
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("BODY");
            xmlWriter.writeElementString("OPEN_FLAG","1");
            xmlWriter.writeEndElement();//body
            xmlWriter.writeEndElement();//CRBANK
            xmlWriter.writeEndDocument();

            //region 二：发送请求报文
            String[] retStrArr = sendToBank(xmlWriter.toXmlString());
            //endregion

            //region 三：解析响应报文
            if (retStrArr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_CODE");
                    String tmpRetInfo = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_MSG");
                    if ("000000".equals(tmpRetCode)) {
                    	FileHelper.writeFile(chkFilePath, retStrArr[1], "utf-8");
                        WriteBankLogLn("电子回单开通成功");
                    } else {
                        WriteBankLogLn("电子回单开通失败, 原因:"+tmpRetInfo);
                    }
                }else{
                    WriteBankLogLn("电子回单开通失败, 原因:"+tmpSbMsg);
                }
            }else{
                WriteBankLogLn("电子回单开通失败, 原因:"+retStrArr[0]);
            }
        }
	}
	
	/**从解压目录提取回单pdf文件*/
	private boolean getReceiptFiles(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay, File pDeDir){
		int sCount = 0;
		int existCount = 0;
		int totalCount = 0;
		File pdfFilesDir = FileCheckHelper.getFirstExistExtDirectory(pDeDir, "pdf", "");
		if(pdfFilesDir == null){
			pdfFilesDir = pDeDir;
		}
		ReceiptDataHelper receiptHelper = null;//回单数据保存类，分区分表
		try{
			receiptHelper = new ReceiptDataHelper(pReqReceipt.reqHeader.tenant, pOneDay);
			double readPdfCostTime = 0.0;
			File[] findFiles = pdfFilesDir.listFiles();
	        if (findFiles != null && findFiles.length > 0) {
	            for (File receiptFile : findFiles) {
	                if (receiptFile.isFile() && receiptFile.getName().toLowerCase().contains(".pdf")) {
	                	totalCount++;
	                	ReceiptData eachData = new ReceiptData();
	                	eachData.ownAct = pReqReceipt.actNum;
	                    eachData.setBusDate(pOneDay);
	                    
	                    String fileName = receiptFile.getName();
	                    String localPath = receiptFile.getAbsolutePath();
	                    //从pdf文件提取信息
	                    Date beginTime = new Date();
	                    String[] arg = PdfGenerateUtil.readFileOfPDF(receiptFile.getAbsolutePath()).split("\r\n");
	                    double secsPast = DateHelper.getDifferSecs(new Date(), beginTime);
	                    readPdfCostTime+=secsPast;
	                    if(secsPast>=0.5){
	                    	WriteBankLogLn("从回单文件"+fileName+"提取信息耗时："+Format.DecimalAmtFormat.format(secsPast)+"秒");
	                    }
	                    if(arg.length>36){
	                    	/*
[30] yyyy-mm-dd HH:mm:ss
[31] 用途
[32] 银行流水号
[33] 付方账号
[34] 金额
[35] 业务种类
[36] 收方账号
[38] 回单验证码
*/
	                    	//判断账号
		                    if(pReqReceipt.actNum.equals(arg[33].trim())){//付方账号
		                    	eachData.moneyWay = "1";
		                    	eachData.oppActNum = arg[36].trim();
		                    }else if(pReqReceipt.actNum.equals(arg[36].trim())){//收方账号
		                    	eachData.moneyWay = "2";
		                    	eachData.oppActNum = arg[33].trim();
		                    }else{
		                    	WriteBankLogLn("从回单文件"+fileName+"提取的付方账号"+arg[33]+"或收方账号"+arg[36]+"与请求"+pReqReceipt.actNum+"不符");
		                    }
		                    //判断日期
		                    String tranDate = arg[30].split(" ")[0];
		                    tranDate = tranDate.replace("-", "").trim();
		                    if(!String.valueOf(eachData.busDate).equals(tranDate)){
		                    	WriteBankLogLn("从回单文件"+fileName+"提取的日期"+tranDate+"与请求"+String.valueOf(eachData.busDate)+"不符");
		                    }
		                    String actCur = pReqReceipt.actCur;
		                    if (StringHelper.isNullOrEmpty(actCur)) {
		                        actCur = "1";
		                    }
		                    eachData.istNbr = arg[32].trim();
	                        eachData.localFile = StringHelper.getRelativePath(localPath, pConfig.localSaveMainDir);
	                        eachData.srcFile = fileName;
	                        eachData.busRef = arg[32].trim();
	                        eachData.receiptNo = arg[32].trim();
	                        eachData.bank = "20127";
	                        eachData.srcSys = "CRBC01";
	                        eachData.amount = new BigDecimal(arg[34].replace(",", ""));
	                        eachData.purpose = arg[31].trim();
	                        eachData.downState = "2";
	                        eachData.downTime = new Date();
	                        
	                        int inRe = receiptHelper.insertIfNotExist(eachData, true);
	                        if(inRe>0){
	                        	sCount++;
	                        }else if(inRe == 0){
	                        	existCount++;
	                        }
	                        WriteBankLogLn(eachData.receiptNo+"写入数据库，影响行数："+inRe);
	                    }else{
	                    	WriteBankLogLn("从回单文件"+fileName+"提取的信息格式不符合预期，提取的文本信息个数："+arg.length);
	                    }
	                }
	            }
	            WriteBankLogLn("遍历"+totalCount+"个pdf文件，其中从pdf提取信息总耗时："+Format.DecimalAmtFormat.format(readPdfCostTime)+"秒");
	        }else{
	        	WriteBankLogLn("解压之后，文件为空");
	        }
		}catch(Exception ex){
        	this.WriteBankLogLn(ex);
        }finally{
        	if(receiptHelper != null){
        		receiptHelper.close();
        	}
        }
		int cmpCount = sCount+existCount;
		if(cmpCount == totalCount && cmpCount>0){
			return true;
		}else{
			WriteBankLogLn("总个数："+totalCount+"，已正常保存："+cmpCount);
			return false;
		}
	}

}
